import api from "../utils/request.js";
import atlas from "@/atlas";
import Store from "@/store.js";
import SET_CONFIG_API from "./config";
import CONFIG from "@/assets/raw/config.js";
import Vue from "vue";
import mockData from "./mock.js";
const isProductDebug = false;
CONFIG["isProductDebug"] = isProductDebug;
let CONFIG_API = SET_CONFIG_API(CONFIG);

const userInfo = {
    uid: "1133581786",
    // 人物影视搜索
    // uid: "32500299916682",
    // 宝贝信息本地测试用户
    // uid: "21200248689561",
    mac: "AC:56:7B:D3:8C:9E",
    cdnType: "",
    // 江苏能力串
    // abilityString: "%257B%2522abilities%2522%253A%255B%2522NxM%2522%252C%25224K-1%257Ccp-TENCENT%2522%255D%252C%2522businessGroupIds%2522%253A%255B%255D%252C%2522deviceGroupIds%2522%253A%255B%25225808%2522%255D%252C%2522districtCode%2522%253A%2522110000%2522%252C%2522labelIds%2522%253A%255B%255D%252C%2522userGroupIds%2522%253A%255B%255D%252C%2522userLabelIds%2522%253A%255B%255D%257D",
    // 广西能力串
    // abilityString:'%7B%22abilities%22%3A%5B%224K-1%7Ccp-TENCENT%7CtimeShift%7CNxM%7CDL-3rd%7Cupgrade14%22%5D%2C%22businessGroupIds%22%3A%5B%5D%2C%22deviceGroupIds%22%3A%5B%224747%22%5D%2C%22districtCode%22%3A%22450100%22%2C%22labelIds%22%3A%5B%22451%22%2C%224518%22%2C%224592%22%2C%2245123%22%2C%2245114%22%2C%224586%22%2C%224532%22%2C%224516%22%5D%2C%22userGroupIds%22%3A%5B%5D%2C%22userLabelIds%22%3A%5B%22451%22%2C%224518%22%2C%224592%22%2C%2245123%22%2C%2245114%22%2C%224586%22%2C%224532%22%2C%224516%22%5D%7D',
    // 海南能力串
    abilityString:
        "%7B%22abilities%22%3A%5B%22Playable-YOUKU%7CPlayable-IQIYI%7CDL-3rd%22%2C%224K-1%7CtimeShift%7CNxM%22%2C%224K-1%7Ccp-TENCENT%22%5D%2C%22businessGroupIds%22%3A%5B%5D%2C%22deviceGroupIds%22%3A%5B%222081%22%5D%2C%22districtCode%22%3A%22350000%22%2C%22labelIds%22%3A%5B%5D%2C%22ucsUserAbilityRefresh%22%3A%221688520185260%22%2C%22userGroupIds%22%3A%5B%22350000%22%5D%2C%22userLabelIds%22%3A%5B%5D%7D",
    templateId: "",
    tvTemplateId: "",
    ottId: "",
    userId: "",
    userToken: "",
    deviceId: "",
    serviceChannelId: "",
    fastapp_package: "",
    fastapp_version: "",
    phone_no: "",
};

// 获取用户信息
const getDeviceInfo = (callback) => {
    const allConfigs = Store.getData("allConfigs");
    atlas
        .getDeviceInfo()
        .then((res) => {
            Vue.Native.callNative(
                "ConsoleModule",
                "log",
                `getDeviceInfo.res:${JSON.stringify(res)}`
            );
            console.log(`getDeviceInfo.res:${JSON.stringify(res)}`);
            if (res.code === "1") {
                const {
                    uid,
                    userId,
                    mac,
                    ottId,
                    userToken,
                    ability,
                    templateId,
                    tvTemplateId,
                    cdnType,
                    cdnType_JS,
                    deviceId,
                    fastapp_package,
                    fastapp_version,
                } = res;
                let _cdnType = "";
                if (allConfigs.PROVINCE === "js") {
                    _cdnType = cdnType_JS;
                } else if (allConfigs.PROVINCE === "hi") {
                    _cdnType = cdnType;
                }
                if (allConfigs.CDN_TYPE_ERROR_TEXT.indexOf(_cdnType) > -1) {
                    _cdnType = "";
                }
                userInfo.uid = uid || "";
                userInfo.mac = mac || "";
                userInfo.userId = userId || "";
                userInfo.deviceId = deviceId || "";
                userInfo.ottId = ottId || "";
                userInfo.userToken = userToken || "";
                userInfo.abilityString = ability || "";
                userInfo.templateId = templateId || "";
                userInfo.tvTemplateId = tvTemplateId || "";
                userInfo.cdnType = _cdnType || "";
                userInfo.fastapp_package = fastapp_package || "";
                userInfo.fastapp_version = fastapp_version || "";
            }
            callback && callback();
        })
        .catch(() => {
            callback && callback();
        });
};

const removeFalsyAttr = (obj) => {
    return Object.entries(obj).reduce((prev, [k, v]) => {
        if (["", undefined].includes(v)) {
            return prev;
        } else {
            return {
                ...prev,
                [k]: v,
            };
        }
    }, {});
};

// 设置bims
const setBims = (data) => {
    const allConfigs = Store.getData("allConfigs");
    if (data) {
        Store.setData("allConfigs", {
            ...allConfigs,
            ...removeFalsyAttr(data),
        });
    }
};

// 获取bims
const getBims = (callback) => {
    const bimsData = Store.getData("bimsData");
    // jsLog("getBims bimsData:", bimsData);
    // 获取bims缓存
    if (bimsData) {
        setBims(bimsData);
        callback && callback();
        return;
    }
    // bims key
    const bimskeys = [
        // "DOMAIN_DMS",
        "DOMAIN_WEATHER",
    ];
    // 批量获取bims下发值
    atlas
        .batchFetchBimsInfo(bimskeys)
        .then((res) => {
            Vue.Native.callNative(
                "ConsoleModule",
                "log",
                "getBims res:" + JSON.stringify(res)
            );
            // jsLog("getBims res:", res);
            if (res) {
                setBims(res);
                callback && callback();
                Store.setData("bimsData", res, true);
            }
        })
        .catch(() => {
            callback && callback();
        });
};

// 获取所有信息，配置信息，下发值，和用户信息
const getAllConfig = (callback) => {
    Vue.Native.callNative("ConsoleModule", "log", "getAllConfig");
    atlas.readLocalFile("assets/raw/config.js").then(({ txt }) => {
        // Vue.Native.callNative("ConsoleModule", "log", "readedConfig" + txt);
        // 从文件生成配置对象
        const _config = new Function(
            txt.replace("module.exports =", "return")
        )();
        if (_config) {
            _config["isProductDebug"] = isProductDebug;
            Store.setData("allConfigs", _config);
            // 2、读取bims下发值，覆盖config.js中的值
            getBims(() => {
                const allConfigs = Store.getData("allConfigs");
                Vue.Native.callNative(
                    "ConsoleModule",
                    "log",
                    "allConfigs:result:" + JSON.stringify(allConfigs)
                );
                // 3、对使用CONFIG中的变量拼接的变量，需要重新赋值。
                CONFIG_API = SET_CONFIG_API(allConfigs);
                // 获取盒子信息
                if (__IS_DEV__) {
                    callback?.();
                } else {
                    getDeviceInfo(callback);
                }
            });
        } else {
            callback?.();
        }
    });
};

function logger(data) {
    const params = {
        ...data,
        uid: userInfo.uid,
        ott_id: userInfo.ottId,
    };
    // jsLog("server logger params", JSON.stringify(params));
    return api(CONFIG_API.log, params, "POST", { httpLevel1: "" });
}

const getUserInfo = () => userInfo;

// ndms 查询瀑布流桌面信息
const getNDMSFlowData = async (data) => {
    const params = {
        ...data,
        abilityString: userInfo.abilityString,
        uid: userInfo.uid,
        mac: userInfo.mac,
        deviceId: userInfo.deviceId,
        custId: userInfo.ottId,
        timeout: Math.abs(CONFIG.DEFAULT_TIMEOUT || 10) * 1e3,
    };
    // 先根据desktopId查询瀑布流数据
    try {
        const res = await api(CONFIG_API.getNDMSFlow, params);
        return res;
    } catch (error) {
        console.log("getNDMSFlowData:error");
        throw new Error(error);
    }
};
// ndms 查询瀑布流桌面信息
const getNDMSTopicData = async (data) => {
    const params = {
        ...data,
        abilityString: userInfo.abilityString,
        uid: userInfo.uid,
        mac: userInfo.mac,
        deviceId: userInfo.deviceId,
        custId: userInfo.ottId,
    };
    // 先根据desktopId查询瀑布流数据
    try {
        const res = await api(CONFIG_API.getNDMSTopic, params);
        return res;
    } catch (error) {
        console.log("getNDMSTopicData:error");
        throw new Error(error);
    }
};

/**
 * 获取地区
 * @returns
 */
const getDistrict = () => {
    return api(CONFIG_API.getDistrict, null, "GET");
};

/**
 * 获取天气
 * @param {*} params { districtCode } 地区编码
 * @returns 
 */
const getWeather = (params) => {
    return api(CONFIG_API.getWeather, {
        abilityString: userInfo.abilityString,
        ...params
    }, "GET")
}

/**
 * 获取股票信息
 * @returns 
 */
const getStockInfo = () => {
    return api(CONFIG_API.getStockInfo, {}, "GET");
}


/**
 * 获取日程数据
 * @returns 
 */
const getScheduleList = (data) => {
    const params = {
        uid: userInfo.uid,
        ...data
    };
    console.log("getScheduleListRequest:params", params)
    return api(CONFIG_API.getScheduleList, params);
}

// 查询地址信息
const getPlaceRoad = async () =>{
    const params = {
        key: CONFIG_API.placeKey,
        level: CONFIG_API.placeLevel,
        name: CONFIG_API.placeName,
        city: CONFIG_API.placeCity,
        adcode: CONFIG_API.placeAdcode,
    }
    try {
        const res = await api(`${CONFIG_API.getPlaceUrl}/traffic/status/road`, params);
        console.log("getPlaceRoad:res", res);
        // return mockData.ll
        return res;
    } catch (error) {
        console.log("getPlaceRoad:error", error);
        throw new Error(error);
    }
}
// 
const getPlaceDriving = async (infos) =>{
    const params = {
        key: CONFIG_API.placeKey,
        origin: infos.origin || CONFIG_API.placeOrigin,
        destination: infos.destination || CONFIG_API.placeDestination,
    }
    try {
        const res = await api(`${CONFIG_API.getPlaceUrl}/direction/driving`, params);
        console.log("getPlaceDriving:res", res);
        // return mockData.ll
        return res;
    } catch (error) {
        console.log("getPlaceDriving:error", error);
        throw new Error(error);
    }
}

const getAddressInfos = async () => {
    const addressRes = await api(`${CONFIG_API.getLLSAPI}address/getAddress`, {
        largeUid: userInfo.uid,
        pageNum: 1,
        pageSize: 99
    }, "POST");
    const records = addressRes?.result?.records;
    const originItem = records.find(item => item.tag === 'MY_HOME');
    const destItem = records.find(item => item.tag === 'COMPANY');
    const originLocation = originItem ? `${originItem.longitude},${originItem.latitude}` : '';
    const destinationLocation = destItem ? `${destItem.longitude},${destItem.latitude}` : '';
    return {
        origin: originLocation,
        destination: destinationLocation,
        originItem: originItem,
        destItem: destItem
    }
}

// /v2/todayRemindInfo
const queryTodayRemindInfo = async () => {
    const params = {
        mac: userInfo.mac || '',
        uid: userInfo.uid || '',
        abilityString: userInfo.abilityString,
    }
    try {
        const res = await api(`${CONFIG_API.getAIAPI}v2/todayRemindInfo`, params);
        console.log("queryTodayRemindInfo:res", res);
        // return mockData.ll
        return res;
    } catch (error) {
        console.log("queryTodayRemindInfo:error", error);
        throw new Error(error);
    }
}


/**
 * 获取节目单数据
 * @returns 
 */
const getProgramList = (data) => {
    const params = {
        ...data,
        abilityString: userInfo.abilityString,
    };
    console.log("getProgramList:params", params)
    return api(CONFIG_API.getProgramList, params);
}

const getAlarmInfo = (data) => {
    return api(`${CONFIG_API.getAIAPI}v1/alarmInfo`, data);
}

/**
 * 获取我的积分信息
 * @returns 
 */
const getMyPointInfo = () => {
  let data = {
    userId: __IS_DEV__ ? "185774055" : userInfo.uid
  }
  return api(CONFIG_API.getMyPointInfo, data, "post");
}


/**
 * @description 获取lls-api的agentViewsconfig配置
 * @returns 
 */
const getAgentViewsConfig = () => {
  return api(`${CONFIG_API.getLLSAPI}dictionary/AGENT_VIEWS_CONFIG`);
}

/**
 * @description 获取lls-api的今日消息通知列表
 * @returns 
 */
const getLifeNoteList = (data) =>{
  let params = {
    ...data,
    uid: userInfo.uid
  }
  try{
    params.cityCode = __IS_DEV__ ? "320100" : JSON.parse(decodeURIComponent(userInfo.abilityString)).districtCode;
  }catch(err){
    console.log("JSON.parse(abilityString) error:" + err.message)
  }
  return api(`${CONFIG_API.getLLSAPI}lifeNote/getNoteList`, params);
}

/**
 * @description 获取当前盒子经纬度
 * @returns 
 */
const getUserInfoLatLng = () =>{
    let params = {
      queryType: "BY_USER",
      fields: "COMMON",
      source: "2222",
      uid: __IS_DEV__ ? "185774055" : userInfo.uid
    }
    console.log("getUserInfoLatLngAction", CONFIG_API.getUserInfoLatLng, params)
    return api(CONFIG_API.getUserInfoLatLng, params);
  }

/**
 * @description 查询小加摘要信息接口
 * @returns
 */
const getAiAbstractList = async () => {
    const params = {
      uid: userInfo.uid || '',
      abilityString: userInfo.abilityString,
      mac: userInfo.mac
  }
  try {
      const res = await api(`${CONFIG_API.getAIAPI}aiAbstractList`, params);
      console.log("getAiAbstractList:res", res);
      return res;
  } catch (error) {
      console.log("getAiAbstractList:error", error);
      throw new Error(error);
  }
}



/**
 * 获取节目单数据
 * @returns 
 */
const getMockListOne = (type) => {
    return new Promise((resolve) => {
        if (type === 1) {
            resolve(mockData.oneMockData);
        }
        if (type === 2) {
            resolve(mockData.twoMockData);
        }
        if (type === 3) {
            resolve(mockData.threeMockData);
        }
        if (type === 4) {
            resolve(mockData.fourMockData);
        }
        if (type === 5) {
            resolve(mockData.fiveMockData);
        }
        if (type === 6) {
            resolve(mockData.sixMockData);
        }
        if (type === 7) {
            resolve(mockData.sevenMockData);
        }
        resolve({});
    }).catch((e) => {
        console.log(e);
    });
}

export default {
    // 首先执行页面逻辑之前，需要调用getAllConfig获取盒子信息和下发值
    getAllConfig,
    logger,
    getUserInfo,
    getNDMSFlowData,
    getNDMSTopicData,
    getDistrict,
    getWeather,
    getStockInfo,
    getScheduleList,
    getPlaceRoad,
    getPlaceDriving,
    queryTodayRemindInfo,
    getProgramList,
    getAlarmInfo,
    getMyPointInfo,
    getAgentViewsConfig,
    getLifeNoteList,
    getUserInfoLatLng,
    getMockListOne,
    getAddressInfos,
    getAiAbstractList
};
